/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginDialog.java
 *
 * Created on Jan 25, 2011, 11:36:08 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleUsuario;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.Usuario;
import br.com.tbp.model.domain.constant.CategoriaDeUsuario;
import br.com.tbp.utils.Atributo;
import br.com.tbp.utils.ImageUtils;
import javax.swing.UIManager;

/**
 *
 * @author Diego Freire
 */
public class LoginDialog extends javax.swing.JDialog {

    public static Usuario usuarioSessao = null;

    public LoginDialog(java.awt.Frame parent, String name, boolean modal) {
        super(parent, name, modal);
        initComponents();
        setLocationRelativeTo(null);

        Atributo.reagirEnter(entrarButton);
        Atributo.reagirEnter(cancelarButton);
        setIconImage(ImageUtils.createIcon("sistema.png").getImage());
        //doAutomaticLogin();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        contentPanel = new javax.swing.JPanel();
        rodapePanel = new javax.swing.JPanel();
        centroPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        loginTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        entrarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        senhaTextField = new javax.swing.JPasswordField();
        msgLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        contentPanel.setLayout(new java.awt.BorderLayout());

        rodapePanel.setBackground(new java.awt.Color(195, 223, 251));
        contentPanel.add(rodapePanel, java.awt.BorderLayout.PAGE_END);

        centroPanel.setLayout(new java.awt.BorderLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/acriel-marca.png"))); // NOI18N
        jLabel2.setToolTipText("Acriel Consultoria - Agente Business");
        jPanel1.add(jLabel2);

        centroPanel.add(jPanel1, java.awt.BorderLayout.PAGE_END);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 204, 255)));

        jLabel3.setText("Entre com suas informações de acesso");

        jLabel4.setText("Login");

        loginTextField.setForeground(new java.awt.Color(0, 0, 0));
        loginTextField.setBorder(javax.swing.BorderFactory.createCompoundBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 204, 255), 1, true), javax.swing.BorderFactory.createEmptyBorder(2, 3, 2, 3)));

        jLabel5.setText("Senha");

        entrarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/key.png"))); // NOI18N
        entrarButton.setText("Entrar");
        entrarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                entrarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        senhaTextField.setBorder(javax.swing.BorderFactory.createCompoundBorder(null, javax.swing.BorderFactory.createCompoundBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 204, 255), 1, true), javax.swing.BorderFactory.createEmptyBorder(2, 3, 2, 3))));
        senhaTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                senhaTextFieldActionPerformed(evt);
            }
        });
        senhaTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                senhaTextFieldFocusGained(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(senhaTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(loginTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                    .addComponent(jLabel5)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                        .addComponent(entrarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelarButton)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(senhaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(entrarButton))
                .addContainerGap())
        );

        msgLabel.setForeground(new java.awt.Color(255, 51, 51));
        msgLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        msgLabel.setPreferredSize(new java.awt.Dimension(41, 18));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(105, 105, 105)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(msgLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(msgLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        centroPanel.add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel3.setBackground(new java.awt.Color(195, 223, 251));
        centroPanel.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        contentPanel.add(centroPanel, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void entrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_entrarButtonActionPerformed
        doLogin();
    }//GEN-LAST:event_entrarButtonActionPerformed

    private void senhaTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_senhaTextFieldActionPerformed
        doLogin();
    }//GEN-LAST:event_senhaTextFieldActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        System.exit(0);
    }//GEN-LAST:event_formWindowClosing

    private void senhaTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_senhaTextFieldFocusGained
        senhaTextField.selectAll();
    }//GEN-LAST:event_senhaTextFieldFocusGained

    public static void main(String args[]) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                LoginDialog dialog = new LoginDialog(new javax.swing.JFrame(), "TBP - Login", true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarButton;
    private javax.swing.JPanel centroPanel;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JButton entrarButton;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JTextField loginTextField;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JPanel rodapePanel;
    private javax.swing.JPasswordField senhaTextField;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>

    private void doLogin() {
        try {
            String user = loginTextField.getText();
            if (user.isEmpty()) {
                msgLabel.setText("O login deve ser informado");
                loginTextField.requestFocus();
                return;
            }
            String password = new String(senhaTextField.getPassword());
            if (password.isEmpty()) {
                msgLabel.setText("A senha deve ser informada");
                senhaTextField.requestFocus();
                return;
            }
            ControleUsuario controle = new ControleUsuario();
            Usuario currentUser = controle.login(user, password);
            if (currentUser != null) {
                this.setUsuarioSessao(currentUser);
                showProgram();
            } else {
                msgLabel.setText("usuário e/ou senha incorreto(s) ou usuário desativado");
                loginTextField.requestFocus();
                this.setUsuarioSessao(null);
            }
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    public static Usuario getUsuarioSessao() {
        return LoginDialog.usuarioSessao;
    }

    public static void setUsuarioSessao(Usuario usuarioSessao) {
        LoginDialog.usuarioSessao = usuarioSessao;
    }

    private void showProgram() {
        limparLogin();
        dispose();
        if (getUsuarioSessao().getCategoria().equals(CategoriaDeUsuario.CONSULTOR)) {
            new MenuConsultor(this).setVisible(true);
        } else {
            new MenuPrincipal(this).setVisible(true);
        }
    }

    private void limparLogin() {
        msgLabel.setText(null);
        loginTextField.setText(null);
        senhaTextField.setText(null);
    }

    private void doAutomaticLogin() {
        loginTextField.setText("admin");
        senhaTextField.setText("deguim");
        entrarButton.requestFocus();
    }
}
